package cn.iocoder.yudao.module.cmt.service.content;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.content.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.content.ContentResourceDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.content.ContentResourceMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class ContentResourceServiceImpl implements ContentResourceService {

    @Resource
    private ContentResourceMapper contentResourceMapper;

    @Override
    public Long createResource(ContentResourceSaveReqVO createReqVO) {
        ContentResourceDO resource = BeanUtils.toBean(createReqVO, ContentResourceDO.class);
        contentResourceMapper.insert(resource);
        return resource.getId();
    }

    @Override
    public void updateResource(ContentResourceSaveReqVO updateReqVO) {
        validateResourceExists(updateReqVO.getId());
        ContentResourceDO updateObj = BeanUtils.toBean(updateReqVO, ContentResourceDO.class);
        contentResourceMapper.updateById(updateObj);
    }

    @Override
    public void deleteResource(Long id) {
        validateResourceExists(id);
        contentResourceMapper.deleteById(id);
    }

    private void validateResourceExists(Long id) {
        if (contentResourceMapper.selectById(id) == null) {
            throw exception(RESOURCE_NOT_EXISTS);
        }
    }

    @Override
    public ContentResourceDO getResource(Long id) {
        return contentResourceMapper.selectById(id);
    }

    @Override
    public PageResult<ContentResourceDO> getResourcePage(ContentResourcePageReqVO pageReqVO) {
        return contentResourceMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteResourceListByIds(List<Long> ids) {
        ids.forEach(this::validateResourceExists);
        contentResourceMapper.deleteBatchIds(ids);
    }

}
